package com.example.server.service.admin.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.server.common.config.exception.BusinessException;
import com.example.server.common.constant.CustomerConstants;
import com.example.server.common.constant.EnableConstants;
import com.example.server.common.constant.Result;
import com.example.server.entity.MenuButton;
import com.example.server.entity.Role;
import com.example.server.mapper.RoleMapper;
import com.example.server.service.admin.MenuButtonService;
import com.example.server.service.admin.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author china.fuyao@outlook.com
 * @date 2020-04-20 10:22
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    MenuButtonService menuButtonService;

    /**
     * 查询角色
     *
     * @param customerId
     * @return
     */
    @Override
    public Result queryRole(Integer customerId) {
        List<Map<String, Object>> mapList = listMaps();
        if (null != mapList && mapList.size() > 0) {
            List<Map> data = new ArrayList<>(mapList.size());
            for (Map<String, Object> map : mapList) {
                Map<String, Object> newMap = new HashMap<>();
                newMap.put("roleId", MapUtil.getInt(map, "role_id"));
                newMap.put("name", MapUtil.getStr(map, "name"));
                newMap.put("createById", MapUtil.getInt(map, "add_uid"));
                newMap.put("status", MapUtil.getInt(map, "status"));
                newMap.put("createTime", MapUtil.getStr(map, "add_time"));
                data.add(newMap);
            }
            return new Result(data);
        }
        return new Result(mapList);
    }

    /**
     * 更新角色菜单按钮
     *
     * @param roleId
     * @param jsonData
     * @param customerId
     * @return
     */
    @Override
    @Transactional
    public Result updateMenu(Integer roleId, String jsonData, Integer customerId) {
        boolean check = JSONUtil.isJsonArray(jsonData);
        if (null == roleId || !check) {
            return Result.Error("请求参数异常");
        }
        JSONArray jsonArray = JSONUtil.parseArray(jsonData);
        List<MenuButton> list = new ArrayList<>(jsonArray.size());
        for (Object o : jsonArray) {
            JSONObject jsonObject = JSONUtil.parseObj(o);
            MenuButton mb = new MenuButton();
            mb.setRoleId(roleId);
            mb.setMenuId(jsonObject.getInt("menuId"));
            mb.setBtnIds(jsonObject.getStr("btnIds"));
            list.add(mb);
        }
        menuButtonService.remove(new QueryWrapper<MenuButton>().eq("role_id", roleId));
        boolean saveBatch = menuButtonService.saveBatch(list);
        if (saveBatch) {
            return Result.OK();
        }
        throw new BusinessException("操作异常回滚");
    }

    /**
     * 添加角色
     *
     * @param name
     * @param customerId
     * @return
     */
    @Override
    public Result addRole(String name, Integer customerId) {
        Role role = getOne(new QueryWrapper<Role>().eq("name", name));
        if (null == role) {
            role = new Role();
            role.setName(name);
            role.setRoleType(CustomerConstants.ADMIN_USER);
            role.setAddUid(customerId);
            role.setStatus(EnableConstants.ENABLE);
            role.setAddTime(LocalDateTime.now());
            boolean save = save(role);
            if (save) {
                return Result.OK();
            }
            return Result.Error();
        }
        return Result.Error("角色已存在");
    }

    /**
     * 更新角色
     *
     * @param roleId
     * @param name
     * @param customerId
     * @return
     */
    @Override
    public Result updateRole(Integer roleId, String name, Integer customerId) {
        Role role = getById(roleId);
        if (null != role) {
            role.setName(name);
            boolean update = updateById(role);
            if (update) {
                return Result.OK();
            }
            return Result.Error();
        }
        return Result.Error("角色不存在");
    }

    /**
     * 删除角色
     *
     * @param roleId
     * @param customerId
     * @return
     */
    @Override
    public Result deleteRole(Integer roleId, Integer customerId) {
        boolean remove = removeById(roleId);
        if (remove) {
            return Result.OK();
        }
        return Result.Error();
    }

    /**
     * 启/禁用角色
     *
     * @param roleId
     * @param enable
     * @param customerId
     * @return
     */
    @Override
    public Result setEnable(Integer roleId, Integer enable, Integer customerId) {
        Role role = getById(roleId);
        if (null != role) {
            role.setStatus(enable);
            boolean update = updateById(role);
            if (update) {
                return Result.OK();
            }
            return Result.Error();
        }
        return Result.Error("角色不存在");
    }
}
